package com.zjitc.service.imp;

import com.rabbitmq.client.ConnectionFactory;
import com.zjitc.common.Gsonal;
import com.zjitc.common.ServerResponse;
import com.zjitc.common.redis.RedisCache;
import com.zjitc.mapper.*;
import com.zjitc.pojo.Collect;
import com.zjitc.pojo.Product;
import com.zjitc.pojo.User;
import com.zjitc.service.UserService;
import com.zjitc.utils.old.*;
import com.zjitc.vo.user.ForgetPasswordDemo;
import com.zjitc.vo.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * Create By IntelliJ IDEA
 *
 * @author: myq
 * @create-Time: 2017/11/7  15:56
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private RedisCache redis;
    @Autowired
    private ConnectionFactory factory;

    /**
     * 交换机
     */
    private final String EXCHANGE_NAME = "Exchange_BigWork";
    private final String REGISTEREMAIL = "email";
    private final String FORGETEMAIL = "forgetEmail";
    private final String PRODUCTS = "products";
    private static final String REDIS_USERS = "users"; //缓存的user
    private static final String COLLECT = "collect";
    private static final String USER = "user"; //session 的user
    private final String MSG = "msg";

    @Override
    public User regiser(User user) {
        user.setUid(Utils.getUUID());
        user.setState("1");
        user.setImg("/static/img/userImg/default.jpg");
        user.setPassword(Utils.getSaltMD5(user.getPassword()));//二次加密
        int success = userMapper.add(user);
        if (success == 1) {
            //更新缓存
            redis.hashset(REDIS_USERS, user.getUsername(), Gsonal.tojson(user));
            user.setPassword("");
            return user;
        }
        return null;
    }

//    @Override
//    public boolean active(String uid, String code) {
//        User user = userMapper.findbyid(uid);
//        if (code.equals(user.getCode())) {
//            user.setState(1);
//            redis.hashset(REDIS_USERS, user.getUsername(), Gsonal.tojson(user));
//            userMapper.update(user);
//            return true;
//        }
//        return false;
//    }

    @Override
    public ServerResponse<User> login(String username, String password, HttpSession session) {
        checkredis();

        String json = redis.hashMapget(REDIS_USERS, username);
        User user = Gsonal.fromJson(json, User.class);
        if (user == null) {
            user = userMapper.findbyusername(username);
        }
        if (user != null) {
            //          开始验证用户与密码
            String realPass = user.getPassword();
            boolean b = Utils.checkPassword(password, realPass);
            if (b) {
                user.setPassword("");
                session.setAttribute(USER, user);
                return ServerResponse.createSuccess();
            }
            return ServerResponse.createError("0");
        }
        return ServerResponse.createError("-1");

    }

    @Override
    public User adminLogin(String username, String password) {
        checkredis();
        String json = redis.hashMapget(REDIS_USERS, username);
        User user = Gsonal.fromJson(json, User.class);
        if (user == null) {
            user = userMapper.findbyusername(username);
        }
        try {
            if (user.getPassword().equals(Utils.encoderByMd5(password))) {
                int hundred = 100;
//                if (user.getState() == hundred) {
//                    return user;
//                }
                return user;//要改
            }
            return null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public User checkUsername(String username) {
        checkredis();
        User user = redis.hashgetObject(REDIS_USERS, username, User.class);
        if (user == null) {
            return userMapper.findbyusername(username);
        }
        return user;
    }

    @Override
    public PageModel<User> findall(int pageid, int count) {
        List<User> users = redis.hashListGetAll(REDIS_USERS, User.class);
        if (users == null) {
            users = userMapper.findAll();
        }
        PageModel<User> pageModel = new PageModel<>(users, count, pageid);
        return pageModel;
    }

    @Override
    public List<User> getUserInfoList() {
        checkredis();
        return redis.hashListGetAll(REDIS_USERS,User.class);
//        return userMapper.findAll();
    }

    @Override
    public int getUserCount() {
       return userMapper.findcount();
    }

    @Override
    public boolean update(User user) {
        int i = userMapper.update(user);
        redis.hashset(REDIS_USERS, user.getUsername(), Gsonal.tojson(user));
        return i == 1;
    }

    @Override
    public User findbyuid(String uid) {
        return userMapper.findbyid(uid);
    }

    @Override
    public boolean deluser(String uid) {
        User user = userMapper.findbyid(uid);
        if(user.getState() == "0") {
            int i = userMapper.deluser(uid);
            redis.delHash(REDIS_USERS, user.getUsername());
            return i==1;
        }else{
            return false;
        }

    }

    @Override
    public ServerResponse checkpassword(String password, String verifypassword) {
        if (!"".equals(password)) {
            if (password.equals(verifypassword)) {
                return ServerResponse.createSuccess("1");
            } else {
                return ServerResponse.createSuccess("0");
            }
        }
        return ServerResponse.createSuccess("0");
    }

//    @Override
//    public void forgetSendEmail(ForgetPasswordDemo demo) {
//        try (
//                Connection connection = factory.newConnection();
//                Channel channel = connection.createChannel()
//        ) {
//            channel.basicPublish(EXCHANGE_NAME, FORGETEMAIL, MessageProperties.PERSISTENT_TEXT_PLAIN,
//                    Gsonal.tojson(demo).getBytes());
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (TimeoutException e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public ServerResponse forgetcheckcode(ForgetPasswordDemo demo, String code) {
        String rediscode = (String) redis.get(demo.getUsername());
        if (code.equalsIgnoreCase(rediscode)) {
            return ServerResponse.createSuccess(demo);
        }
        return ServerResponse.createError("-1");
    }

    @Override
    public String finduidByusername(String username) {
        User user = userMapper.findbyusername(username);
        if (user != null) {
            return user.getUid();
        }
        return null;

    }

    @Override
    public boolean forgetResetPassword(User user) {
        checkredis();
        String username = userMapper.findusernameByuid(user.getUid());
        User redisuser = redis.hashgetObject(REDIS_USERS, username, User.class);
        if (redisuser == null) {
            redisuser = userMapper.findbyusername(username);
        }
        try {
            redisuser.setPassword(Utils.encoderByMd5(user.getPassword()));
            redis.hashset(REDIS_USERS, redisuser.getUsername(), Gsonal.tojson(redisuser));
            userMapper.update(redisuser);
            return true;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public ServerResponse resetPassword(String username, String oldPassword, String newPassword,
                                        HttpSession session) {
        checkredis();
        User user = redis.hashgetObject(REDIS_USERS, username, User.class);
        if (user == null) {
            user = userMapper.findbyusername(username);
        }
        try {
            if (user.getPassword().equals(Utils.encoderByMd5(oldPassword))) {
                user.setPassword(Utils.encoderByMd5(newPassword));
                redis.hashset(REDIS_USERS, username, Gsonal.tojson(user));
                userMapper.update(user);
                session.removeAttribute(USER);
                return ServerResponse.createSuccess();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return ServerResponse.createError();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return ServerResponse.createError();
        }
        return ServerResponse.createError("旧密码错误");
    }

    @Override
    public ModelAndView searchMyCollect(HttpSession session, String page) {
        ModelAndView mv = new ModelAndView("/jsp/searchCollect");
        User user = (User) session.getAttribute(USER);
        if (user == null) {
            List<Collect> collectList = redis.hashListGetAll(COLLECT, Collect.class);
            if (collectList == null) {
                collectList = collectMapper.findCollectbyuid(user.getUid());
            }
            List<Product> productList = new ArrayList<>();
            collectList.forEach(collect -> {
                Product product = redis.hashgetObject(PRODUCTS, collect.getPid(), Product.class);
                productList.add(product);
            });
            PageModel pageModel = new PageModel(productList, Integer.parseInt(page));
            mv.addObject("pagemodel", pageModel);
        } else {
            mv.setViewName("jsp/login");
        }
        return mv;
    }

    @Override
    public ServerResponse sendPhoneCode(String phone, HttpSession session) {
        boolean flag = checkPhone(phone);
        if (flag) {
            String code = Utils.getCode();
//            try{
//                SmsMessage.SendSmsMessage(phone,code);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//                return ServerResponse.createError("发送短信出错了");
//            } catch (ClientException e) {
//                e.printStackTrace();
//                return ServerResponse.createError("发送短信出错了");
//            }
            System.out.println("手机号= " + phone);
            System.out.println("验证码 = " + code);
            redis.set(phone, code, 300);
            return ServerResponse.createSuccess();
        }
        return ServerResponse.createError();
    }

    @Override
    public boolean checkCode(String phone, String code) {
        String getCode = (String) redis.get(phone);
        if (code.equals(getCode)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean updatePassword(String uid, String password) {
        User user = userMapper.findbyid(uid);
        String saltMD5 = Utils.getSaltMD5(password);
        user.setPassword(saltMD5);
        int i = userMapper.update(user);
        redis.hashset(REDIS_USERS,user.getUsername(),Gsonal.tojson(user));
        return i == 1;
    }

    @Override
    public int updateIntegral(Integer integral, String uid) {
        userMapper.updateIntegral(integral,uid);
        return integral;
    }

    @Override
    public String updateState(String username) {
        checkredis();
        User user = redis.hashgetObject(REDIS_USERS, username, User.class);
        String state = user.getState();
        if("0".equals(state)){
            user.setState("1");
        }else{
            user.setState("0");
        }
        redis.hashset(REDIS_USERS,username,Gsonal.tojson(user));
        return state;

    }

    @Override
    public List<User> findUserSearch(String username) {
        return userMapper.findSearch(username);
    }

    @Override
    public String getUserPhone(String uid) {
        return userMapper.getUserphone(uid);
    }

    private boolean checkPhone(String phone) {
        List<User> users = redis.hashListGetAll(USER, User.class);
        for (User user : users) {
            if (user.getPhone().equals(phone)) {
                return false;
            }
        }
        return true;
    }


    private void checkredis() {
        if (!redis.exists(REDIS_USERS)) {
            RedisAuto.usersRedis(userMapper, redis, REDIS_USERS);
        }
    }


}
